#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import subprocess
import time

def run_command(cmd, description=""):
    """运行命令并返回结果"""
    print(f"执行: {description}")
    print(f"命令: {cmd}")
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
        if result.returncode == 0:
            print(f"✓ 成功: {result.stdout.strip()}")
            return True, result.stdout
        else:
            print(f"✗ 失败: {result.stderr.strip()}")
            return False, result.stderr
    except subprocess.TimeoutExpired:
        print("✗ 命令执行超时")
        return False, "超时"
    except Exception as e:
        print(f"✗ 执行异常: {e}")
        return False, str(e)

def check_environment():
    """检查环境"""
    print("=== 检查环境 ===")
    
    # 检查项目目录
    project_dir = "/home/ubuntu/zlymes/mesmaster"
    if os.path.exists(project_dir):
        print(f"✓ 项目目录存在: {project_dir}")
    else:
        print(f"✗ 项目目录不存在: {project_dir}")
        return False
    
    # 切换到项目目录
    os.chdir(project_dir)
    print(f"✓ 切换到项目目录: {os.getcwd()}")
    
    # 检查manage.py
    if os.path.exists("manage.py"):
        print("✓ manage.py文件存在")
    else:
        print("✗ manage.py文件不存在")
        return False
    
    return True

def check_conda_env():
    """检查conda环境"""
    print("\n=== 检查conda环境 ===")
    
    # 检查conda
    success, output = run_command("which conda", "检查conda命令")
    if not success:
        print("✗ conda未找到")
        return False
    
    # 激活环境并检查Python
    conda_cmd = "source ~/miniconda3/etc/profile.d/conda.sh && conda activate mes"
    success, output = run_command(f"{conda_cmd} && python --version", "检查Python版本")
    if not success:
        print("✗ Python环境检查失败")
        return False
    
    # 检查Django
    success, output = run_command(f"{conda_cmd} && python -c 'import django; print(django.VERSION)'", "检查Django版本")
    if not success:
        print("✗ Django环境检查失败")
        return False
    
    return True

def check_django_settings():
    """检查Django设置"""
    print("\n=== 检查Django设置 ===")
    
    conda_cmd = "source ~/miniconda3/etc/profile.d/conda.sh && conda activate mes"
    
    # 检查基础设置
    settings_files = [
        "settings_mes_basic",
        "settings_full_mes", 
        "settings_django_with_mes"
    ]
    
    for settings in settings_files:
        success, output = run_command(
            f"{conda_cmd} && python manage.py check --settings={settings}",
            f"检查设置文件: {settings}"
        )
        if not success:
            print(f"✗ 设置文件 {settings} 检查失败")
            return False
    
    return True

def check_services():
    """检查服务状态"""
    print("\n=== 检查服务状态 ===")
    
    ports = [8004, 8005, 8006]
    services = ["基础MES", "完整MES", "Django管理"]
    
    for i, port in enumerate(ports):
        success, output = run_command(f"lsof -t -i:{port}", f"检查端口{port}")
        if success and output.strip():
            print(f"✓ {services[i]}服务正在运行 (端口 {port})")
        else:
            print(f"✗ {services[i]}服务未运行 (端口 {port})")

def start_services():
    """启动服务"""
    print("\n=== 启动MES服务 ===")
    
    conda_cmd = "source ~/miniconda3/etc/profile.d/conda.sh && conda activate mes"
    
    services = [
        {"port": 8004, "settings": "settings_mes_basic", "name": "基础MES服务"},
        {"port": 8005, "settings": "settings_full_mes", "name": "完整MES服务"},
        {"port": 8006, "settings": "settings_django_with_mes", "name": "Django管理服务"}
    ]
    
    # 停止旧服务
    print("停止旧服务...")
    run_command("pkill -f 'python manage.py runserver'", "停止旧服务")
    time.sleep(2)
    
    for service in services:
        print(f"\n启动{service['name']} (端口 {service['port']})...")
        
        # 运行数据库迁移
        migrate_cmd = f"{conda_cmd} && python manage.py migrate --settings={service['settings']}"
        success, output = run_command(migrate_cmd, f"运行数据库迁移")
        
        # 启动服务
        start_cmd = f"nohup bash -c \"{conda_cmd} && python manage.py runserver 0.0.0.0:{service['port']} --settings={service['settings']}\" > /tmp/mes_{service['port']}.log 2>&1 &"
        success, output = run_command(start_cmd, f"启动{service['name']}")
        
        time.sleep(3)  # 等待服务启动
        
        # 检查服务是否启动
        success, output = run_command(f"lsof -t -i:{service['port']}", f"检查{service['name']}状态")
        if success and output.strip():
            print(f"✓ {service['name']}启动成功")
        else:
            print(f"✗ {service['name']}启动失败")
            # 显示日志
            log_cmd = f"tail -n 10 /tmp/mes_{service['port']}.log"
            run_command(log_cmd, f"查看{service['name']}日志")

def show_access_info():
    """显示访问信息"""
    print("\n=== 服务访问信息 ===")
    print("基础MES服务: http://175.27.138.86:8004/")
    print("基础MES管理后台: http://175.27.138.86:8004/admin/")
    print("完整MES服务: http://175.27.138.86:8005/")
    print("完整MES管理后台: http://175.27.138.86:8005/admin/")
    print("Django管理服务: http://175.27.138.86:8006/admin/")
    print("\n管理员账户: admin / admin123")
    print("\n日志文件:")
    print("- /tmp/mes_8004.log")
    print("- /tmp/mes_8005.log")
    print("- /tmp/mes_8006.log")

def main():
    print("=== MES服务检查和启动工具 ===")
    
    # 检查环境
    if not check_environment():
        print("环境检查失败，无法继续")
        return
    
    # 检查conda环境
    if not check_conda_env():
        print("conda环境检查失败，无法继续")
        return
    
    # 检查Django设置
    if not check_django_settings():
        print("Django设置检查失败，但尝试启动服务")
    
    # 检查当前服务状态
    check_services()
    
    # 启动服务
    start_services()
    
    # 再次检查服务状态
    print("\n=== 最终服务状态 ===")
    check_services()
    
    # 显示访问信息
    show_access_info()

if __name__ == "__main__":
    main() 